import { Header } from "antd/es/layout/layout";
import mainlogo from "../../pictures/logo/mainlogo.png";
import { useEffect, useRef, useState } from "react";
import "../../css/app/AppHeader.css";
import RequestUtils from "../../utils/RequestUtils";
import { useNavigate } from "react-router-dom";

/**
 * 系统头部 - 适中数量的粒子背景
 */
const AppHeader = () => {
    const canvasRef = useRef(null);
    const particles = useRef([]);
    const animationFrameId = useRef(null);
    const [userNickname, setUserNickname] = useState("加载中...");
    const [isLoading, setIsLoading] = useState(true);
    const mousePos = useRef({ x: null, y: null });
    const navigate = useNavigate();

    // 获取用户信息
    useEffect(() => {
        const fetchUserInfo = async () => {
            try {
                const userInfo = await RequestUtils.getCurrentUserInfo();
                if (userInfo && userInfo.userNickname) {
                    setUserNickname(userInfo.userNickname);
                } else {
                    setUserNickname("获取失败");
                }
            } catch (error) {
                console.error("获取用户信息失败:", error);
                setUserNickname("获取失败");
            } finally {
                setIsLoading(false);
            }
        };

        fetchUserInfo();
    }, []);

    // 优化版粒子背景 - 增加数量同时保持性能
    useEffect(() => {
        const canvas = canvasRef.current;
        const ctx = canvas.getContext('2d');

        // 柔和但清晰的粒子颜色
        const particleColors = [
            'rgba(59, 130, 246, 0.7)',  // 适中透明度的蓝色
            'rgba(139, 92, 246, 0.7)',  // 适中透明度的紫色
            'rgba(236, 72, 153, 0.7)',  // 适中透明度的粉色
            'rgba(16, 185, 129, 0.7)',  // 适中透明度的绿色
        ];

        // 柔和的连线颜色
        const lineColors = [
            'rgba(59, 130, 246, 0.4)',
            'rgba(139, 92, 246, 0.4)',
            'rgba(236, 72, 153, 0.4)',
            'rgba(16, 185, 129, 0.4)',
        ];

        // 设置Canvas尺寸
        const setCanvasSize = () => {
            const rect = canvas.getBoundingClientRect();
            const dpr = window.devicePixelRatio || 1;
            canvas.width = rect.width * dpr;
            canvas.height = rect.height * dpr;
            ctx.scale(dpr, dpr);
            canvas.style.width = `${rect.width}px`;
            canvas.style.height = `${rect.height}px`;
        };

        setCanvasSize();
        window.addEventListener('resize', setCanvasSize);

        // 粒子数量增加到40个（比30个更密集，同时保持性能）
        const createParticles = (count = 40) => {
            const rect = canvas.getBoundingClientRect();
            particles.current = [];

            for (let i = 0; i < count; i++) {
                const colorIndex = Math.floor(Math.random() * particleColors.length);
                const color = particleColors[colorIndex];

                // 保持中等大小（1.5-3px），避免增加渲染压力
                const radius = Math.random() * 1.5 + 1.5;
                // 平缓的运动速度
                const speed = 0.2 + Math.random() * 0.4;

                particles.current.push({
                    x: Math.random() * rect.width,
                    y: Math.random() * rect.height,
                    radius,
                    speedX: (Math.random() - 0.5) * speed,
                    speedY: (Math.random() - 0.5) * speed,
                    color,
                    originalColor: color,
                    colorIndex,
                    pulse: 0,
                    pulseDir: 0.015,   // 轻微脉冲效果
                    pulseMax: 0.2      // 小幅度脉冲
                });
            }
        };

        createParticles();

        // 鼠标移动事件（限制响应频率，平衡交互与性能）
        let lastMouseMove = 0;
        const handleMouseMove = (e) => {
            const now = Date.now();
            if (now - lastMouseMove < 50) return; // 每50ms响应一次
            lastMouseMove = now;

            const rect = canvas.getBoundingClientRect();
            mousePos.current = {
                x: e.clientX - rect.left,
                y: e.clientY - rect.top
            };
        };

        canvas.addEventListener('mousemove', handleMouseMove);

        // 绘制粒子（保持轻量渲染）
        const drawParticles = () => {
            const rect = canvas.getBoundingClientRect();
            ctx.clearRect(0, 0, rect.width, rect.height);

            particles.current.forEach(particle => {
                // 轻微脉冲效果
                particle.pulse += particle.pulseDir;
                if (particle.pulse > particle.pulseMax || particle.pulse < 0) {
                    particle.pulseDir = -particle.pulseDir;
                }

                // 适度发光（控制阴影消耗）
                ctx.shadowColor = particle.color.replace('0.7', '0.4');
                ctx.shadowBlur = 6 + particle.radius * 3;

                // 绘制粒子
                ctx.beginPath();
                ctx.arc(particle.x, particle.y, particle.radius + particle.pulse, 0, Math.PI * 2);

                // 简化渐变计算
                const rgb = particle.color.match(/\d+/g);
                const r = rgb[0];
                const g = rgb[1];
                const b = rgb[2];

                const gradient = ctx.createRadialGradient(
                    particle.x, particle.y, 0,
                    particle.x, particle.y, particle.radius + particle.pulse
                );
                gradient.addColorStop(0, `rgba(${r}, ${g}, ${b}, 0.9)`);
                gradient.addColorStop(1, particle.color);

                ctx.fillStyle = gradient;
                ctx.fill();

                // 重置阴影
                ctx.shadowBlur = 0;
            });

            // 绘制粒子间的连线（限制距离，减少计算）
            particles.current.forEach((particle, i) => {
                particles.current.forEach((otherParticle, j) => {
                    if (i < j) {
                        const distance = Math.sqrt(
                            Math.pow(particle.x - otherParticle.x, 2) +
                            Math.pow(particle.y - otherParticle.y, 2)
                        );

                        // 保持连线距离限制（100px内），避免数量增加导致连线暴增
                        if (distance < 100) {
                            const opacity = 0.15 - distance / 666;
                            if (opacity > 0) {
                                const colorIndex = Math.floor((particle.colorIndex + otherParticle.colorIndex) / 2) % lineColors.length;
                                const baseColor = lineColors[colorIndex];

                                ctx.beginPath();
                                ctx.moveTo(particle.x, particle.y);
                                ctx.lineTo(otherParticle.x, otherParticle.y);

                                ctx.shadowColor = baseColor.replace('0.4', '0.2');
                                ctx.shadowBlur = 3;

                                ctx.strokeStyle = baseColor.replace('0.4', opacity.toString());
                                ctx.lineWidth = 0.8;
                                ctx.stroke();

                                ctx.shadowBlur = 0;
                            }
                        }
                    }
                });

                // 鼠标与粒子交互（保持轻量计算）
                if (mousePos.current.x !== null && mousePos.current.y !== null) {
                    const mouseDist = Math.sqrt(
                        Math.pow(particle.x - mousePos.current.x, 2) +
                        Math.pow(particle.y - mousePos.current.y, 2)
                    );

                    if (mouseDist < 120) {
                        const hoverColor = particle.color.replace('0.7', '0.9');
                        particle.color = hoverColor;

                        const opacity = 0.2 - mouseDist / 600;
                        if (opacity > 0) {
                            ctx.beginPath();
                            ctx.moveTo(mousePos.current.x, mousePos.current.y);
                            ctx.lineTo(particle.x, particle.y);

                            ctx.shadowColor = hoverColor.replace('0.9', '0.3');
                            ctx.shadowBlur = 4;

                            ctx.strokeStyle = `rgba(255, 255, 255, ${opacity})`;
                            ctx.lineWidth = 0.6;
                            ctx.stroke();

                            ctx.shadowBlur = 0;
                        }
                    } else {
                        particle.color = particle.originalColor;
                    }
                }
            });
        };

        // 更新粒子位置（保持平缓运动）
        const updateParticles = () => {
            const rect = canvas.getBoundingClientRect();

            particles.current.forEach(particle => {
                // 轻微鼠标排斥力
                if (mousePos.current.x !== null && mousePos.current.y !== null) {
                    const dx = mousePos.current.x - particle.x;
                    const dy = mousePos.current.y - particle.y;
                    const distance = Math.sqrt(dx * dx + dy * dy);

                    if (distance < 120) {
                        const force = 0.03 * (1 - distance / 120);
                        particle.speedX -= (dx / distance) * force;
                        particle.speedY -= (dy / distance) * force;
                    }
                }

                // 平缓移动
                particle.x += particle.speedX;
                particle.y += particle.speedY;

                // 边界反弹
                if (particle.x < 0 || particle.x > rect.width) {
                    particle.speedX = -particle.speedX * 0.9;
                }

                if (particle.y < 0 || particle.y > rect.height) {
                    particle.speedY = -particle.speedY * 0.9;
                }

                // 轻微随机运动
                particle.speedX += (Math.random() - 0.5) * 0.02;
                particle.speedY += (Math.random() - 0.5) * 0.02;

                // 限制最大速度
                const maxSpeed = 0.8;
                const speed = Math.sqrt(particle.speedX * particle.speedX + particle.speedY * particle.speedY);
                if (speed > maxSpeed) {
                    particle.speedX = (particle.speedX / speed) * maxSpeed;
                    particle.speedY = (particle.speedY / speed) * maxSpeed;
                }
            });

            drawParticles();
            animationFrameId.current = requestAnimationFrame(updateParticles);
        };

        updateParticles();

        // 清理
        return () => {
            cancelAnimationFrame(animationFrameId.current);
            window.removeEventListener('resize', setCanvasSize);
            canvas.removeEventListener('mousemove', handleMouseMove);
        };
    }, []);

    return (
        <Header className="app-header">
            {/* 粒子背景 */}
            <canvas ref={canvasRef} className="particles-bg" style={{ zIndex: 1, pointerEvents: 'none' }} />

            <div className="header-content" style={{ zIndex: 2 }}>
                <div className="logo-container">
                    <img
                        src={mainlogo}
                        alt="系统Logo"
                        className="logo-image"
                    />
                </div>
                <h1 className="system-title">
                    gengzp-three 运维管理中心
                </h1>
            </div>

            <div className="user-info-container"
                 onClick={() => navigate("/personal")}
                 style={{ zIndex: 2 }}
            >
                <div className="user-avatar">
                    <span>{userNickname?.charAt(0) || 'X'}</span>
                </div>
                <div className="user-name-text">
                    {userNickname}
                </div>
            </div>
        </Header>
    );
};

export default AppHeader;